package com.goldcn.interceptor;

import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.jwt.JWTSigner;
import com.google.common.primitives.Longs;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/13.
 */
public class SystemContext {
    private static final ThreadLocal request = new ThreadLocal();

    public static void setRequest(HttpServletRequest _request) {
        request.set(_request);
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest _request = (HttpServletRequest) request.get();
        return _request;
    }

    public static void removeRequest() {
        request.remove();
    }

    public static void removeAll() {
        removeRequest();
    }

    public static Long getCompanyID() {
        String companyID = null;
        String ver = getRequest().getHeader("ver");
        if (CommonUtils.isNotEmpty(ver) && ver.equals("2.0")) {
            companyID = getRequest().getHeader("companyID");
            //System.out.println("get companyID from header. id=" + companyID);
        }
        //System.out.println("request  url=="+getRequest().getRequestURI()+"       companyID ======  " + companyID);
        if(CommonUtils.isEmpty(companyID)){
            throw new ServiceException("获取公司ID失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return Longs.tryParse(companyID);
    }

    public static Map<String,Object> getToken() {
        String token = null;
        Map<String, Object> map=new HashMap<>();
        String ver = getRequest().getHeader("ver");
        if (CommonUtils.isNotEmpty(ver) && ver.equals("2.0")) {
            token = getRequest().getHeader("token");
            System.out.println("get companyID from header. id=" + token);
        }
        //System.out.println("request  url=="+getRequest().getRequestURI()+"       companyID ======  " + companyID);
/*        if(CommonUtils.isEmpty(token)){
            throw new ServiceException("获取Token失败", RestConst.ErrorCode.SERVICE_FAIL);
        }*/
        if (token!=null) {
            JWTSigner jwtSigner = new JWTSigner();
            map = jwtSigner.getFromTk(token);
        }
        return map;
    }

}
